package com.tanhua.server.controller;

import com.tanhua.domain.UserInfo;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.server.service.UserInfoService;
import com.tanhua.server.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoService userInfoService;

    /**
     * 发送验证码
     * @param map
     * @return
     */
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map map){
        //1.获取手机号
        String phone = (String) map.get("phone");
        //2.调用service方法
        userService.sendCode(phone);
        return ResponseEntity.ok(null);
        //3.返回数据
    }

    /**
     * 登录校验
     * @param map
     * @return
     */
    @PostMapping("/loginVerification")
    public ResponseEntity loginVerification(@RequestBody Map map){
        //获取请求参数
        String phone = (String) map.get("phone");
        String code = (String) map.get("verificationCode");
        //调用service层方法
        Map retMap = userService.loginVerification(phone,code);
        //封装数据返回
        return ResponseEntity.ok(retMap);

    }

    /**
     * 添加新用户
     * @param userInfo
     * @param token
     * @return
     */
    @PostMapping("/loginReginfo")
    public ResponseEntity loginReginfo(@RequestBody UserInfo userInfo,
                                       @RequestHeader ("Authorization") String token){
        //从ThreadLocal中获取用户id
        Long id = UserHolder.getUserId();

        userInfo.setId(id);

        userInfoService.save(userInfo);
        return ResponseEntity.ok(null);

    }

    /**
     * 人脸校验
     * @param headPhoto
     * @param token
     * @return
     * @throws IOException
     */
    @PostMapping("/loginReginfo/head")
    public ResponseEntity head(MultipartFile headPhoto, @RequestHeader("Authorization") String token) throws IOException {
        //从ThreadLocal中获取用户id
        Long id = UserHolder.getUserId();

        userInfoService.updateHead(headPhoto,id);

        return ResponseEntity.ok().body(null);

    }


}
